package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.TCloudRole;
import model.TParentInfo;
import model.VCloudParentStudent;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import annotation.Log;
import persistent.factory.DAOFactory;
import util.office.NewReadExcel;
import util.toolkit.Constant;
import util.toolkit.Expression;
import util.toolkit.ResponseJSON;

/**
 * 学生家长管理请求处理类
 * @author zl
 * @since 2018/10/2 17:07
 */
@Controller
@RequestMapping(value="/sysparentmanagement")
public class SysParentManagementController {
	
	/**
	 * 添加家长处理控制类
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 * @author djf
	 * @since 2018/12/4
	 */
	//TODO 添加家长处理控制类
	@Log(operationType = Constant.OPERTATION_ADD, operationDescribe = "添加一个家长", 
			operationClassPath = "controller.SysTitleManagementController.addParent(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "家长管理/家长信息添加")
	@RequestMapping(value = "/addParent")
	public String addParent(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression exp2 = new Expression();
		
		try {		
			String schoolid=req.getParameter("schoolid");
			
			if(schoolid!=null && !schoolid.equals("")){
				exp2.andEqu("schoolid", schoolid, String.class);
				exp2.andEqu("parentid", Constant.PARENT, Integer.class);
				
				List<TCloudRole> cloudrolelist=DAOFactory.getCloudRoleDAO().getRoleListByStrWhere(exp2.toString());
				List<VCloudParentStudent> listparentstudent=new ArrayList<VCloudParentStudent>();
				
				String realName = req.getParameter("realName");
				String sex = req.getParameter("sex");
				String phone = req.getParameter("phone");
				String studentlistid=req.getParameter("studentlistid");
				String relationship=req.getParameter("relationship");
				
				
				if (realName != null && !realName.equals("") && sex != null && !sex.equals("")
						&& phone != null && !phone.equals("") && studentlistid!=null && !studentlistid.equals("")
						&& relationship!=null && !relationship.equals("") ) {
					String strstudentlistid[]=studentlistid.split(",");
				
					for(int i=0;i<strstudentlistid.length;i++){
						VCloudParentStudent parentstudent=new VCloudParentStudent();
						parentstudent.setParRealName(realName);
						parentstudent.setParSex(sex);
						parentstudent.setPhone(phone);
						parentstudent.setSchoolid(schoolid);
						parentstudent.setStuid(strstudentlistid[i]);
						parentstudent.setRelation(relationship);
						listparentstudent.add(parentstudent);
					}
			
					boolean row = DAOFactory.getParentInfoDAO().addParent(listparentstudent,
							cloudrolelist.get(0).getId());
					if (row) {
						result.put("code", ResponseJSON.FLAG_SUCC);
						result.put("msg", "家长添加成功！");
					} else {
						result.put("code", ResponseJSON.FLAG_FAIL);
						result.put("msg", "家长添加失败，请重试！");
					}
				}else{
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "家长添加失败，请重试！");
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_FAIL);
			result.put("msg", "查询未知异常，家长添加失败，请重试！");
		}

		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
	}
	
	/**
	 * 根据家长id得到一条家长对象
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 * @author djf
	 * @since 2018/12/4
	 */
	//TODO 根据家长id得到一条家长对象
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "根据家长id得到一条家长对象", 
			operationClassPath = "controller.SysTitleManagementController.getAParentById(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "家长管理/家长信息查看")
	@RequestMapping(value = "/getaparentbyid")
	public String getAParentById(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression exp = new Expression();
		
		try {
			String schoolid=req.getParameter("schoolid");
			String parentid=req.getParameter("parentid");
			
			if(parentid!=null && !parentid.equals("") && schoolid!=null && !schoolid.equals("")){
				exp.andEqu("parinfoid", Integer.parseInt(parentid), Integer.class);
				exp.andEqu("schoolid", schoolid, String.class);
				String strwhere = exp.toString();

				List<TParentInfo> list = DAOFactory.getParentInfoDAO().getParentList(strwhere);
				if (list != null && list.size() > 0) {
					result.put("code", 0);
					result.put("msg", "查询成功");
					result.put("count", list.size());
					JSONArray jsonArray = JSONArray.fromObject(list);
					result.element("data", jsonArray);
				} else {
					result.put("code", 1);
					result.put("msg", "无查询结果！");
				}
			}
			else {
				result.put("code", 1);
				result.put("msg", "出现异常，查询失败，请重试！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 1);
			result.put("msg", "出现异常，查询失败，请重试！");
		}
		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
	} 
	
	/**
	 * 家长信息修改控制类
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 家长信息修改控制类
	@Log(operationType = Constant.OPERTATION_UPDATE, operationDescribe = "修改一个家长信息", 
			operationClassPath = "controller.SysTitleManagementController.updateParent(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "家长管理/家长信息查看")
	@RequestMapping(value="/updateparent")
	public String updateParent(Model model,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");
		
		JSONObject result=new JSONObject();
		
		try {
			String parinfoid=req.getParameter("parinfoid");
			String realName=req.getParameter("realname");
			String sex=req.getParameter("sex");
			String birthday=req.getParameter("birthday");
			String address=req.getParameter("address");

			
			if(parinfoid!=null && !parinfoid.equals("") && realName!=null && !realName.equals("") 
					&& sex!=null && !sex.equals("") && birthday!=null && !birthday.equals("")
					&& address!=null && !address.equals("")){
				TParentInfo parent2=DAOFactory.getParentInfoDAO().getTParentInfo(Integer.parseInt(parinfoid));

				parent2.setRealName(realName);
				parent2.setSex(sex);
				parent2.setBirthday(birthday);
				parent2.setAddress(address);
				
				boolean row=DAOFactory.getParentInfoDAO().updateParent(parent2);
				if(row){
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "家长信息修改成功！");
				}else{
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "家长信息修改失败！");
				}
			}else{
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "家长信息修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "家长信息修改失败！");
		}
		
		PrintWriter write=resp.getWriter();
		write.print(result);
		return null;
	}
	
	/**
	 * 家长信息删除控制类
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 家长信息删除控制类
	@Log(operationType = Constant.OPERTATION_DELETE, operationDescribe = "删除一个家长信息", 
			operationClassPath = "controller.SysTitleManagementController.deleteParent(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "家长管理/家长信息查看")
	@RequestMapping(value="/deleteparent")
	public String deleteParent(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		
		try {
			String parid = req.getParameter("parentid");
			if (parid != null && !parid.equals("")) {
				if(DAOFactory.getParentInfoDAO().deleteParent(Integer.parseInt(parid))){
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "删除成功！");
				}
				else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "删除失败，存在外键引用，请删除引用后重试！");
				}
			}
			else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "删除失败，家长编号不能为空！");
			}
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_FAIL);
			result.put("msg", "删除失败，存在外键引用，请删除引用后重试！");
			e.printStackTrace();
		}
		
		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
		
	}
	
	/**
	 * 根据条件查询学生家长控制类
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 根据条件查询学生家长控制类
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "根据条件查询学生家长信息", 
			operationClassPath = "controller.SysTitleManagementController.getParentByWhere(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "家长管理/家长信息查看")
	@RequestMapping(value="/getparentbywhere")
	public String getParentByWhere(Model model,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");
		
		JSONObject result=new JSONObject();
		Expression exp=new Expression();
		
		try {
			String schoolid=req.getParameter("schoolid");
			String gradename=req.getParameter("gradename");
			String classid=req.getParameter("classid");
			String userName=req.getParameter("userName");
			
			String currentPage=req.getParameter("page");
			String pageSize=req.getParameter("limit");
			
			if(currentPage!=null && !currentPage.equals("") && pageSize!=null && !pageSize.equals("")){
				if(schoolid!=null && !schoolid.equals("")){
					exp.andEqu("schoolid", schoolid, String.class);
				}
				if(gradename!=null && !gradename.equals("")){
					exp.andEqu("gradename", gradename, String.class);
				}
				if(classid!=null && !classid.equals("")){
					exp.andEqu("classid", classid, String.class);
				}
				if(userName!=null && !userName.equals("")){
					exp.andLeftBraLike("parUserName", userName, String.class);
					exp.orRightBraLike("parRealName", userName, String.class);
				}
				exp.orderByDesc("schoolName");
				exp.orderByDesc("gradename");
				exp.orderByDesc("className");
				String strWhere = exp.toString();
				List<VCloudParentStudent> list=DAOFactory.getParentInfoDAO().getParentStudent(
						strWhere, Integer.parseInt(currentPage), Integer.parseInt(pageSize));
				List<VCloudParentStudent> listSize=DAOFactory.getParentInfoDAO().getParentStudent(strWhere);
				if (list != null && list.size() > 0) {
					result.put("code", 0);
					result.put("msg", "查询成功");
					result.put("count", listSize.size());
					JSONArray jsonArray = JSONArray.fromObject(list);
					result.element("data", jsonArray);
				} else {
					result.put("code", 1);
					result.put("msg", "无查询结果");
				}
			} 
			else{
				result.put("code", 1);
				result.put("msg", "无查询结果");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			result.put("code", 2);
			result.put("msg", "出现未知异常，查询失败");
		}
		PrintWriter write=resp.getWriter();
		write.print(result);
		return null;
	}
	
	/**
	 * 根据查询条件得到学生家长信息
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 根据查询条件得到学生家长信息
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "根据查询条件得到学生家长信息", 
			operationClassPath = "controller.SysTitleManagementController.getParentStudent(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "家长管理/家长信息查看")
	@RequestMapping(value="/getparentstudent")
	public String getParentStudent(Model model,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");
		
		JSONObject result=new JSONObject();
		Expression exp=new Expression();

		try {
			String stuid=req.getParameter("stuid");
			String parentid=req.getParameter("parentid");
			
			if(stuid!=null && !stuid.equals("")){
				exp.andEqu("stuid", stuid, String.class);
			}
			if(parentid!=null && !parentid.equals("")){
				exp.andEqu("parentid", Integer.parseInt(parentid), Integer.class);
			}
			String strwhere=exp.toString();
			
			List<VCloudParentStudent> list=DAOFactory.getParentInfoDAO().getParentStudent(strwhere);
			if(list!=null && list.size()>0){
				result.put("code", 0);
				result.put("msg", "查询成功");
				result.put("count", list.size());
				JSONArray jsonArray = JSONArray.fromObject(list);
				result.element("data", jsonArray);
			}else{
				result.put("code", 1);
				result.put("msg", "无查询结果");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 1);
			result.put("msg", "无查询结果");
		}
		PrintWriter write=resp.getWriter();
		write.print(result);
		return null;
	}
	
	/**
	 * Excel数据导入到数据库(2018-12-12 徐震霖)
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO Excel数据导入到数据库(2018-12-12 徐震霖)
	@Log(operationType = Constant.OPERTATION_ADD, operationDescribe = "Excel数据导入到数据库", 
			operationClassPath = "controller.SysTitleManagementController.savestuList(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "家长管理/家长学生关系导入")
	@RequestMapping(value = "/savestulist")
	public String savestuList(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		HttpSession session = req.getSession();
		Expression exp = new Expression();
		
		try {
			String schoolid = req.getParameter("schoolid");
			if (schoolid != null && !schoolid.equals("") && !schoolid.equals("00") && !schoolid.equals("0")) {
				exp.andEqu("schoolid", schoolid, String.class);
				exp.andEqu("parentid", Constant.PARENT, Integer.class);
				
				List<TCloudRole> rolelist = DAOFactory.getCloudRoleDAO().getRoleListByStrWhere(exp.toString());
				List<VCloudParentStudent> psList = (List<VCloudParentStudent>) session.getAttribute("psList");
				
				List<VCloudParentStudent> failList = DAOFactory.getParentInfoDAO().batchImport(psList, rolelist.get(0).getId());
				if (failList != null && failList.size() > 0) {
					result.put("code", 1);
					result.put("msg", "存在重复记录或发生其他错误，导入失败，请核对数据后重试！");
					session.setAttribute("psfailList", failList);
				} else {
					result.put("code", 0);
					result.put("msg", "导入成功！");
				}
			}
			else {
				result.put("code", 1);
				result.put("msg", "学校编号不能为空！");
			}
		} catch (Exception e) {
			result.put("code", 1);
			result.put("msg", "存在重复数据，导入失败！");
			e.printStackTrace();
		}

		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;

	}
	
	/**
	 * 把Excel导入到前-table表格里(2018-12-12 徐震霖)
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 把Excel导入到前台table表格里(2018-12-12 徐震霖)
	@RequestMapping(value = "/excelloadtable")
	public String excelLoadTable(Model model, HttpServletRequest req,
			HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		HttpSession session = req.getSession();
		String op = req.getParameter("op");

		try {
			if (op.equals("0")) {
				List<VCloudParentStudent> psList = (List<VCloudParentStudent>) session.getAttribute("psList");
				if (psList != null && psList.size() > 0) {
					result.put("code", 0);
					result.put("msg", "获取成功！");
					result.put("count", psList.size());
					JSONArray jsonArray = JSONArray.fromObject(psList);
					result.element("data", jsonArray);
				} else {
					result.put("code", 1);
					result.put("msg", "出现异常，获取失败，请重试！");
				}
			}
			else {
				List<VCloudParentStudent> psList = (List<VCloudParentStudent>) session.getAttribute("psfailList");
				if (psList != null && psList.size() > 0) {
					result.put("code", 0);
					result.put("msg", "获取成功！");
					result.put("count", psList.size());
					JSONArray jsonArray = JSONArray.fromObject(psList);
					result.element("data", jsonArray);
				} else {
					result.put("code", 1);
					result.put("msg", "出现异常，获取失败，请重试！");
				}
			}
		} catch (Exception e) {
			result.put("code", 1);
			result.put("msg", "出现异常，获取失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;

	}
	
	/**
	 * 把Excel转换为List(2018-12-12 徐震霖)
	 * @param model
	 * @param req
	 * @param resp
	 * @param file
	 * @return
	 * @throws IOException
	 */
	// TODO 把Excel转换为List(2018-12-12 徐震霖)
	@RequestMapping(value = "/getexceltablelist")
	public String getExcelTableList(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		HttpSession session = req.getSession();
		NewReadExcel nre = new NewReadExcel();
		List<VCloudParentStudent> psList = new ArrayList<VCloudParentStudent>();
		List<String> outerList = null;

		try {
			String schoolid = req.getParameter("schoolid");
			String classid = req.getParameter("classid");
			if (classid != null && !classid.equals("") && !classid.equals("00") && !classid.equals("0") 
					&& schoolid != null && !schoolid.equals("") && !schoolid.equals("00") && !schoolid.equals("0")) {
				List excelList = nre.readExcel(req, resp);
				for (int i = 0; i < excelList.size(); i++) {
					outerList = (List<String>) excelList.get(i);
					VCloudParentStudent vps = new VCloudParentStudent();
					for (int j = 0; j < outerList.size(); j++) {
						switch (j) {
						case 0:
							vps.setStuid(outerList.get(j).toString());
							break;
						case 1:
							vps.setStuRealName(outerList.get(j).toString());
							break;
						case 2:
							vps.setStuSex(outerList.get(j).toString());
							break;
						case 3:
							vps.setParRealName(outerList.get(j).toString());
							break;
						case 4:
							vps.setParSex(outerList.get(j).toString());
							break;
						case 5:
							vps.setPhone(outerList.get(j).toString());
							break;
						case 6:
							vps.setRelation(outerList.get(j).toString());
							break;
						case 7:
							vps.setClassName(outerList.get(j).toString());
							break;
						case 8:
							vps.setGradename(outerList.get(j).toString());
							break;
						}
						vps.setClassid(classid);
						vps.setSchoolid(schoolid);
					}
					psList.add(vps);
				}
				if (psList != null && psList.size() > 0) {
					result.put("code", 0);
					result.put("msg", "获取成功！");
					result.put("count", psList.size());
					JSONArray jsonArray = JSONArray.fromObject(psList);
					result.element("data", jsonArray);
					session.setAttribute("psList", psList);
				} else {
					result.put("code", 1);
					result.put("msg", "获取失败，请重试！");
				}
			}
			else {
				result.put("code", 1);
				result.put("msg", "学校或班级信息不能为空 ！");
			}
		} catch (Exception e) {
			result.put("code", 1);
			result.put("msg", "出现异常，获取失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
	}

}
